<?php


namespace models\Business;


use models\DAO\AlibabaproductactivityModel;
use models\Exception\Business\AlibabaactivityException;
use models\Exception\Business\AlibabaproductactivityException;
use models\Exception\Business\AlibabaproductException;
use models\Exception\DAO\ModelDriverException;
use models\Exception\DAO\ModelException;
use models\Exception\DAO\ModelReflectionException;
use models\Exception\DAO\ModelSqlException;
use models\Exception\Service\ServiceException;
use models\Exception\Transformer\TransformerException;
use models\Service\AlibabaactivityService;
use models\Service\AlibabaproductactivityService;
use Yaf\Registry;

class AlibabaActivity
{

    /**
     * 1688 商品参与活动数据 入库
     * @param array $parameters
     * @throws AlibabaproductactivityException
     * @throws ModelDriverException
     * @throws ModelException
     * @throws ModelReflectionException
     * @throws ModelSqlException
     * @throws ServiceException
     * @throws TransformerException
     */
    static public function collectProductActivity($parameters = [])
    {
        $model = AlibabaproductactivityModel::getInstance();
        $conn  = $model->getConn();
        $conn->beginTransaction();
        try {
            if (!isset($parameters['activity_id']) || empty($parameters['activity_id']))
                throw new AlibabaproductactivityException(AlibabaactivityException::ALIBABAACTIVITY_ID_IS_EMPTY, AlibabaactivityException::ALIBABAACTIVITY_ID_IS_EMPTY_NO);
            if (!isset($parameters['product_id']) || empty($parameters['product_id']))
                throw new AlibabaproductactivityException(AlibabaproductException::ALIBABAPRODUCT_ID_IS_EMPTY, AlibabaproductException::ALIBABAPRODUCT_ID_IS_EMPTY_NO);

            // 获取activity_id数组
            $rules     = [
                ['field' => 'activity_id', 'op' => 'eq', 'data' => $parameters['activity_id']],
                ['field' => 'product_id', 'op' => 'eq', 'data' => $parameters['product_id']]
            ];
            $condition = ['groupOp' => 'AND', 'rules' => $rules];

            $product_activity_exists = AlibabaproductactivityService::getInstance()->getOne($condition);

            if ($product_activity_exists) {
                $sql = "DELETE FROM `alibabaproductactivity` WHERE `product_id` = '" . $parameters['product_id'] .
                    "' AND `activity_id` = '" . $parameters['activity_id'] . "'";
                Registry::get('db_log')->info("删除alibabaproductactivity表的数据.sql: " . $sql);
                $conn->executeQuery($sql);
            }

            $sql = "INSERT INTO `alibabaproductactivity` (`" . implode("`, `", array_keys($parameters)) . "`) VALUES ('" . implode("', '", array_values($parameters)) . "')";
            Registry::get('db_log')->info("添加alibabaproductactivity表的数据.sql:" . $sql);
            $conn->executeQuery($sql);

            $conn->commit();

        } catch (AlibabaproductactivityException $e) {
            throw $e;
        } catch (ModelDriverException $e) {
            $conn->rollback();
            throw $e;
        } catch (ModelException $e) {
            throw $e;
        } catch (ModelReflectionException $e) {
            throw $e;
        } catch (ModelSqlException $e) {
            $conn->rollback();
            throw $e;
        } catch (ServiceException $e) {
            throw $e;
        } catch (TransformerException $e) {
            throw $e;
        }

    }

    /**
     * 1688促销活动信息入库
     * @param array $parameters
     * @throws ModelDriverException
     * @throws ModelException
     * @throws ModelReflectionException
     * @throws ModelSqlException
     * @throws ServiceException
     * @throws TransformerException
     */
    static public function collectActivity($parameters = [])
    {
        try {
            // 获取activity_id数组
            $activity_id_arr = array_column($parameters, 'activity_id');
            $activity_id_arr = array_filter(array_unique($activity_id_arr));

            // 查询attribute_id是否存在于数据库
            if (count($activity_id_arr) == 1) {
                $attribute_exists['data'][] = AlibabaactivityService::getInstance()->getOne(implode(',', array_values($activity_id_arr)));
            } else {
                $attribute_exists = AlibabaactivityService::getInstance()->getList(1, count($activity_id_arr), 'desc', 'activity_id',
                    ['groupOp' => 'AND', 'rules' => [
                        ['field' => 'activity_id', 'op' => 'in', 'data' => implode(',', $activity_id_arr)]]]);
            }

            $batch_update_arr = $batch_insert_arr = [];
            // attribute存在
            if (!empty($attribute_exists['data'])) {
                $exists_attribute_id_arr = array_column($attribute_exists['data'], 'activity_id');
                foreach ($parameters as $activity_info) {
                    // 已存在的商品写入更新数据
                    if (in_array($activity_info['activity_id'], $exists_attribute_id_arr)) {
                        array_push($batch_update_arr, $activity_info);
                    } // 不存在的商品写入插入数组
                    else
                        array_push($batch_insert_arr, $activity_info);
                }
            } else {
                $batch_insert_arr = $parameters;
            }

            // 更新数组存在
            if (!empty($batch_update_arr)) {
                // 更新数组长度大于1，批量插入
                if (count($batch_update_arr) > 1)
                    AlibabaactivityService::getInstance()->batchUpdate($batch_update_arr);
                // 更新数组长度等于1，单条更新
                else {
                    $update_arr  = array_values($batch_update_arr);
                    $update_arr  = $update_arr[0];
                    $activity_id = $update_arr['activity_id'];
                    AlibabaactivityService::getInstance()->update($update_arr, $activity_id);
                }
            }

            // 插入数据存在
            if (!empty($batch_insert_arr))
                // 批量插入数据
                AlibabaactivityService::getInstance()->batchInsert($batch_insert_arr);
        } catch (ModelDriverException $e) {
            throw $e;
        } catch (ModelException $e) {
            throw $e;
        } catch (ModelReflectionException $e) {
            throw $e;
        } catch (ModelSqlException $e) {
            throw $e;
        } catch (ServiceException $e) {
            throw $e;
        } catch (TransformerException $e) {
            throw $e;
        }

    }

    /**
     * 查询活动信息
     * @param $product_id
     * @return array|mixed|null
     * @throws AlibabaproductactivityException
     * @throws ModelDriverException
     * @throws ModelException
     * @throws ModelReflectionException
     * @throws ModelSqlException
     * @throws ServiceException
     * @throws TransformerException
     */
    static public function getActivityByPid($product_id)
    {
        try {
            return AlibabaproductactivityService::getInstance()->getOne($product_id);
        } catch (ModelDriverException $e) {
            throw $e;
        } catch (ModelException $e) {
            if ($e->getCode() == ModelException::DATA_NOT_EXISTS_NO)
                throw new AlibabaproductactivityException(AlibabaproductactivityException::ALIBABAPRODUCTACTIVITY_IS_NOT_EXISTS, AlibabaproductactivityException::ALIBABAPRODUCTACTIVITY_IS_NOT_EXISTS_NO);
            throw $e;
        } catch (ModelReflectionException $e) {
            throw $e;
        } catch (ModelSqlException $e) {
            throw $e;
        } catch (ServiceException $e) {
            throw $e;
        } catch (TransformerException $e) {
            throw $e;
        }
    }
}
